package servlets;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tools.Config;

/**
 * Servlet implementation class PositionningServlet
 */
public class PositionningServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public PositionningServlet() {super();}
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);}
	
	/** Where shit happens */
	protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		// This try catch block look into the /proc/net/arp file to find the mac adress of mobile device
		// from its ip that we know with request.getRemoteAddr()
		String macAddr= "";
		try{
			// Open the file
			FileInputStream fstream = new FileInputStream("/proc/net/arp");
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			// ignore the first line
			br.readLine();
			String strLine;
			boolean found = false;
			//Read File Line By Line while we didnt found the MD ip
			while ((strLine = br.readLine()) != null && !found){
				// We split the line on a space to isolate ip (1 word in the line)
				// and the mac adress (4th word in the line)
				String[] res = strLine.split(" ");
				
				if(request.getRemoteAddr().equals(res[0]))
					found = true;
				
				if(found){
					// if found we search the mac adresse which is the 4th word not empty
					int count = 0;
					for(int i=0; i < res.length && !found; i++){
						if(!res[i].equals("")){
							if(count != 3)
								count++;
							else{
								macAddr = res[i];
							}
						}
					}
				}
				
			}
			//Close the input stream
			in.close();
		}catch (Exception e){//Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
		
		// Preparing the message to send to every AP (by broadcast)
				String message = "GET;"+macAddr;
				
		// Broadcasting the packet to 192.168.1.255
		try {
			InetAddress addr = InetAddress.getByName("192.168.1.255");
			DatagramPacket packetToSend = new DatagramPacket(message.getBytes(), message.getBytes().length, addr, Config.PORT_SEND);
			DatagramSocket socket = new DatagramSocket(Config.PORT_SEND);
			socket.send(packetToSend);
			socket.close();
		} catch (Exception e1) {e1.printStackTrace();}
		
		// We wait for the AP to send the response (that will be handle by APListener)
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {e.printStackTrace();}
		
		// A this point the servlet looks into the Database, and then compute informations to determine x and y
		// (not implemented)
		
		// We use a random for test purposes
		Random rand = new Random();
		int x = rand.nextInt(460);
		int y = rand.nextInt(650);
		int mid = 1;
		
		// We send back the positioning informations to the mobile device
		out.println(x+";"+y+";"+mid);
	}

}
